package top.huxy.boot.config.interceptor;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname CrossDomainInterceptor
 * @Description 跨域请求拦截
 * @Date 2021/8/30 19:20
 * @Created by huxy
 */
public class CrossDomainInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //设置允许任意域名访问
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        //允许请求方法
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        //允许携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");

        //设置允许的请求头。
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Accept, Origin, User-Agent, Content-Range, Content-Disposition, Content-Description");

        //阻止options请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }

        //顺便设置下响应内容
        response.setContentType("application/json");
//        response.setCharacterEncoding("utf-8");
        return true;
    }
}
